import React, {useContext, useEffect, useState,memo} from 'react';
import { withRouter} from 'react-router-dom';
import {List, Avatar, Space, Row, Col, Image, message, Spin} from 'antd';
import {
    MessageOutlined,
    LikeOutlined,
    RetweetOutlined,
    StarOutlined, StarFilled, LikeFilled
} from '@ant-design/icons';
import style from './index.module.css'
import CommentModal from '../../commentModal/index'
import {PostContext} from "../index";
import {get} from "../../../utils/get";
import {post} from "../../../utils/post";
const Type =['ISLIKE','ISFAVOR'];
const TweetsList = (props) => {
    const [isShow,changeIsShow] = useState(false);
    const [list,changeList]=useState([]);
    const [whichTweet,changeTweet]=useState("");//当前选择哪条推文回复
    const [page,changePage] =useState(1);
    const [total,setTotal] = useState(0);
    const [spinning,changeSpinning]=useState(false)
    const token = localStorage.getItem('TOKEN')
    const userUid=JSON.parse(localStorage.getItem('USERDATA'))?.userUid;
    const {mypost,setPost} = useContext(PostContext)
    useEffect(()=>{
        if(props.type===0){
            changeSpinning(true);
            get(`/share/list?page=${page}&limit=15`,token).then(
                res=> {
                    console.log(res);
                    if(res.data.code===0)
                    {
                            let data =res.data.page.list
                            if(mypost==""){
                                setTotal(res.data.page.totalCount)
                                changeList(data);
                            }
                            else {
                                setPost("")
                            }
                    }
                    else message.error(res.data.errorMsg)
                    changeSpinning(false);
                }
            )
        }
        //我的收藏
        else if(props.type===1){
            const token = localStorage.getItem('TOKEN')
             get(`/share/myFavor?page=${page}&limit=15`,token).then(res=>{
                if(res.data.code===0)
                {
                    changeList(res.data.page.list)
                    setTotal(res.data.page.totalCount)
                }
            })
        }
        //搜索功能
        else if(props.searchTotal){
           changeList(props.data.slice((page-1)*15,page*15));
           setTotal(props.searchTotal)
        }
    },[props,page])

    const  {showImg} =props
    //展示时间
    const myTime=(time)=>{
        return time?.substring(0,10)+" "+time?.substring(11,19);
    }

    const IconText = ({ icon, text }) => (
        <Space>
            {React.createElement(icon)}
            {text}
        </Space>
    );

    const jump = (shareID)=>{
        const token =localStorage.getItem('TOKEN')
        if(token)
            props.history.push(`/index/detail/${shareID}`)
        else
            props.history.push(`/visit/detail/${shareID}`)
    }
    const checkType = (tweet_id,isLike,type)=>{
        if(!token) {
            message.info('请先登录')
            return;
        }
        if(props.type===1||props.type===0||props.type===3)
            changeLikeOrFavor(tweet_id,isLike,type)
        else
            message.info('功能尚未开放')
    }
    const checkType2 = (shareId) => {
        if(!token){
            message.info('请先登录')
            return;
        }
        if(props.type===0||props.type===1||props.type===3)
        {   changeIsShow(true);
            changeTweet(shareId)
        }
    }
    const changeLikeOrFavor=async (tweet_id,isLike,type)=>{//处理点赞
        const token= localStorage.getItem('TOKEN')
        if(type===Type[0]){//点赞
            if(!isLike){
                const res= await post(`/share/${tweet_id}/like`,{},token)
                console.log(res);
                if(res.data.code===0){
                    list.map(item=>{
                        if(item.shareId===tweet_id){
                            item.isLike=true;
                            item.likeCount++;
                        }
                    })
                    changeList([...list])
                }
                else{
                        message.error(res.data.errorMsg);
                    }
            }else{//取消点赞
                const res= await post(`/share/${tweet_id}/unlike`,{},token)
                if(res.data.code===0) {
                    list.map(item => {
                        if (item.shareId === tweet_id) {
                            item.isLike = false;
                            item.likeCount--;
                        }
                    })
                    changeList([...list])
                }else message.error(res.data.errorMsg)
            }
        }
        else if(type===Type[1]){//收藏
            if(!isLike){
                const res=await post(`/share/${tweet_id}/favor`,{},token)
                if(res.data.code===0){
                    list.map(item=>{
                        if(item.shareId===tweet_id){
                            item.isFavor=true;
                            item.favorCount++;
                        }
                    })
                    changeList([...list])
                }
                else   message.error(res.data.errorMsg)
            }
            else{
                const res =await post(`/share/${tweet_id}/unFavor`,{},token)
                if(res.data.code===0){
                    list.map(item=>{
                        if(item.shareId===tweet_id){
                            item.isFavor=false;
                            item.favorCount--;
                        }
                    })
                    changeList([...list])
                }
            else message.error(res.data.errorMsg)
            }
        }
    }
    //渲染favor组件
    const renderFavor = (isFavor,shareId,sharePostStatus,id)=>{
        if(sharePostStatus!==0&&id!==userUid)
            return  <StarOutlined className={style.cantLike} onClick={()=>message.error('该分享不允许收藏')}/>
        else if(isFavor)
            return <StarFilled style={{color:'#ffd75a'}} onClick={()=>checkType(shareId,isFavor,Type[1])}/>
        else return <StarOutlined onClick={()=>checkType(shareId,isFavor,Type[1])}/>
    }
    //渲染like组件
    const renderLike = (isLike,shareId,sharePostStatus,id)=>{
        if(sharePostStatus===2&&id!==userUid)
            return  <LikeOutlined className={style.cantLike} onClick={()=>message.error('该分享不允许点赞')}/>
        else if(isLike)
            return <LikeFilled style={{color:'#0170fe'}}onClick={()=>checkType(shareId,isLike,Type[0])}/>
        else return <LikeOutlined onClick={()=>checkType(shareId,isLike,Type[0])}/>
    }
    //渲染评论组件
    const renderComment=(shareId,sharePostStatus,id)=>{
        if(sharePostStatus!==0&&id!==userUid)
         return <MessageOutlined className={style.cantLike}/>
         else return <MessageOutlined onClick={()=>checkType2(shareId,sharePostStatus)}/>
    }
    return(
        <div>
            <Spin spinning={spinning} tip="浏览器也在开摆中......">
            <List className={`${style.body}`}
            bordered={true}
            size ="small"
            pagination={{
                pageSize: 15,
                total:total,
                onChange:(page)=>{
                    changePage(page);
                }
            }}
            dataSource={list}
            renderItem={item => {
                const{favorCount,likeCount,content,commentCount,isLike,isFavor,shareId,nickname,avatar,updateTime,images,sharePostStatus,userUid} =item
                return(
                <List.Item className={`${style.bodyItem}`} key={shareId}>
                    <List.Item.Meta className={`${style.meta}`}
                                    avatar={<Avatar onClick={()=>{jump(shareId)}}
                                                    src={avatar} />}
                                    title={<a onClick={()=>{jump(shareId)}}>{nickname}</a>}
                    />
                    {/*时间*/}
                    <p className={style.time} onClick={()=>jump(shareId)}>{showImg&&myTime(updateTime)}</p>
                    {/*推文内容*/}
                    <div className={style.content} onClick={()=>jump(shareId)}>
                        {content}
                    </div>
                    {/*图片*/}
                    <Row className={style.image}>
                        {//与运算，当数据为评论数据时，不展示图片
                            images&&images.map((value,key) => {
                                return(
                                    <Col className="gutter-row" key={key} span={8}>
                                        <Image
                                            className={`${style.img}`}
                                            key={key}
                                            width={160}
                                            height={160}
                                            alt="照片"
                                            src={value}
                                        />
                                    </Col>
                                )
                            })
                        }
                    </Row>
                    {/*点赞转发一栏*/}
                    {
                        <div className={style.action}>
                            <Row>
                                <Col className="gutter-row" span={6} >
                                    {/* {
                                        isFavor? (<StarFilled style={{color:'#ffd75a'}}
                                                              onClick={()=>checkType(shareId,isFavor,Type[1])}/>)
                                            :(<StarOutlined onClick={()=>checkType(shareId,isFavor,Type[1])}/>)
                                    } */}
                                    {renderFavor(isFavor,shareId,sharePostStatus,userUid)}
                                    <span>{favorCount}</span>
                                </Col>
                                <Col className="gutter-row" span={6} >
                                    {renderLike(isLike,shareId,sharePostStatus,userUid)}
                                    <span>{likeCount}</span>
                                </Col>
                                <Col className="gutter-row"  span={6}>
                                    {renderComment(shareId,sharePostStatus,userUid)}
                                    <span>{commentCount}</span>
                                </Col>
                                <Col className="gutter-row" span={6} onClick={()=>message.info('转发功能仍未完善，敬请期待')}>
                                    <IconText icon={RetweetOutlined} text={0} key="list-vertical-upload"/>
                                </Col>
                            </Row>
                        </div>
                    }
                </List.Item>
            )}
            }
        />
            </Spin>
            <CommentModal show={isShow} type={0}  msgId={whichTweet} changeShow={(value)=>changeIsShow(value)}/>
        </div>
    );
}

export default withRouter(memo(TweetsList));
